<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller;

use buwang\base\AdminBaseController;
use buwang\traits\JwtTrait;
use think\facade\View;
use app\manage\model\AuthGroupNode;
use app\manage\model\AuthGroup;
use app\manage\model\AuthNode;
use app\manage\model\Admin as AdminModel;
use app\manage\model\AuthGroupAccess;
use app\manage\model\Token;
use buwang\service\UserService;
use app\Request;

class Admin extends AdminBaseController
{
    public function user()
    {
        if (request()->isAjax()) {
            $page = request()->get('page/d', 1);
            $limit = request()->get('limit/d', 10);
            $topAdminId = config('auth.super_admin_id');//超级管理员id
            $topAdminRoleId = config('auth.super_admin_role_id');//超级管理员角色
            $where = request()->get();
            unset($where['page']);
            unset($where['limit']);
            foreach ($where as $k => $v) {
                if (!$v && $v !== '0' && $v !== 0 && $v !== false) {
                    unset($where[$k]);
                }
            }
            try {
                //得到所有登录用户
                $groups = AdminModel::valiWhere()->where($where)->page($page, $limit)->order('id asc')->select()->toArray();
                $total = AdminModel::valiWhere()->where($where)->count();
                //返回数据
                $list = array();
                foreach ($groups as $group) {
                    $data = $group;
                    if ($group['id'] == $topAdminId) {
                        $data['is_super'] = true;
                    } else {
                        $data['is_super'] = false;
                    }
                    $data['is_super_role'] = false;

                    $data['rules'] = [];
                    $data['auth_group_access'] = [];
                    //查询所有角色，以逗号拼接
                    $rules = AuthGroupAccess::valiWhere()->where('uid', $group['id'])->where('scopes', 'admin')->column('group_id');
                    $names = AuthGroupAccess::valiWhere()->where('uid', $group['id'])->where('scopes', 'admin')->column('name');
                    if ($rules) {
                        $data['rules'] = $rules;
                        //如果拥有超级管理员角色则也是超管
                        if (in_array($topAdminRoleId, $rules)) $data['is_super_role'] = true;
                    }
                    if ($names) {
                        $data['auth_group_access'] = $names;
                    }
                    //过滤下密码
                    if(isset($data['password'])) unset($data['password']);
                    $list[] = $data;
                }
            } catch (\think\db\exception\PDOException $e) {
                return $this->error('查询失败', ['errorMsg' => $e->getData()]);
            }
            //var_dump($list);die;
            $data = compact("total", 'list');
            return $this->success('success', $data);
        }

        return view('');
    }

    /**
     * 编辑管理组
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $topAdminId = config('auth.super_admin_id');//超级管理员id
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AdminModel::updateAdmin($param, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(AdminModel::getError());
            }

        }
        $id = $this->request->get('id');
        $data = AuthGroupAccess::getFind($id);
        if ($topAdminId == $id) $is_super = true; else $is_super = false;
        $list = AdminModel::select()->toArray();
        return view('form', ['data' => $data, 'list' => $list, 'is_super' => $is_super]);
    }

    /**
     * 添加管理组
     * @return \think\Response
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $result = AdminModel::createAdmin($param, true);
            if ($result) {
                return $this->success('操作成功');
            } else {
                return $this->error(AdminModel::getError());
            }
        }
        return view('form', ['is_super' => false]);
    }

    /**
     * 删除
     * @menu true
     * @param int $ids 主键,删除多行时,拼接
     */
    public function delete($ids = 0)
    {
        if (request()->isPost()) {
            if (!$ids) return $this->error('参数有误');
            $list = AdminModel::where('id', 'in', $ids)->select();
            if (!$list) return $this->error('记录不存在');
            $topAdminId = config('auth.super_admin_id');//超级管理员id
            if (in_array($topAdminId, explode(",", $ids))) return $this->error('无法删除超级管理员');
            AdminModel::startTrans();
            try {
                foreach ($list as $item) {
                    AdminModel::destroy($item['id']);
                    //删除角色中间表
                    $ids = AuthGroupAccess::where('uid', $item['id'])->where('scopes', 'admin')->column('id');
                    if ($ids) {
                        AuthGroupAccess::destroy($ids);
                    }
                }
                AdminModel::commit();
            } catch (\Exception $e) {
                AdminModel::rollback();
                return $this->error('删除失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success();
        }
    }

    /**
     * 更改开启状态
     *
     * @return \think\Response
     */
    public function setStatus()
    {
        if (request()->isAjax()) {
            $id = input('id/d');
            $data = AdminModel::find($id);
            if ($data['status'] === 0) {
                $data['status'] = 1;
            } elseif ($data['status'] === 1) {
                $data['status'] = 0;
            };
            $data->save();
            return $this->success('successful');

        }
    }
}
